package com.umpay.privi.ejb.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.umpay.common.persist.ibatis.DataAccessException;
import com.umpay.privi.common.BeanManager;
import com.umpay.privi.common.Constants;
import com.umpay.privi.common.ReqMessage;
import com.umpay.privi.common.ResMessage;
import com.umpay.privi.common.RetCode;
import com.umpay.privi.common.XmlData;
import com.umpay.privi.dao.on.sys.ResourceDao;
import com.umpay.privi.dao.on.sys.UserDao;
import com.umpay.privi.exception.BusinessException;
import com.umpay.privi.helper.ReqParaCheckHelper;
import com.umpay.privi.model.sys.Resource;
import com.umpay.privi.model.sys.User;
import com.umpay.privi.service.sys.ResourceServiceRemote;
import com.umpay.privi.util.SeqUtil;

/** 
 * 资源Ejb
 * @author 肖明 2013-05-07
 */
@TransactionManagement(TransactionManagementType.BEAN)
public class ResourceServiceBean implements ResourceServiceRemote{
	
	private static Logger logger = LoggerFactory.getLogger(ResourceServiceBean.class);

	public ResMessage queryAllSysResources(ReqMessage reqMessage) {
		logger.info("[ResourceServiceBean]queryAllSysResources请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "ResourceServiceBean.queryAllSysResources.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResourceDao resourceDao = BeanManager.getBean("resourceDao", ResourceDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			List<Resource> resources = resourceDao.findAllSysResources(reqMessage.getReqMap());
			resMessage.put(XmlData.RESULT_LIST, resources);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[ResourceServiceBean]queryAllSysResources响应数据："+resMessage);
		return resMessage;
	}

	public ResMessage queryResourcesByUserId(ReqMessage reqMessage) {
		logger.info("[ResourceServiceBean]queryResourcesByUserId请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "ResourceServiceBean.queryResourcesByUserId.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = reqMessage.getString(XmlData.SYSID);
			String userId = reqMessage.getString(XmlData.USERID);
			User user = userDao.get(userId);
			if(user==null || !sysId.equals(user.getSysId().toString())){
				resMessage.setRetCode(RetCode.NO_DATA);
				resMessage.setRetMsg("用户不存在或不属于本系统");
				logger.info("[ResourceServiceBean]queryResourcesByUserId响应数据："+resMessage);
				return resMessage;
			}
			List<Integer> resources = userDao.findResourcesByUserId(userId);//查询用户资源
			resMessage.put("resourceList", resources);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[ResourceServiceBean]queryResourcesByUserId响应数据："+resMessage);
		return resMessage;
	}

	public ResMessage statement(ReqMessage reqMessage) {
		ResourceDao resourceDao = BeanManager.getBean("resourceDao", ResourceDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sql = reqMessage.getString("sql");
			resourceDao.statement(sql);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("执行成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[ResourceServiceBean]statement响应数据："+resMessage);
		return resMessage;
	}
	/** 
	 * desc:根据条件查询对应的资源
	 * <p>创建人：liucong 创建日期：Apr 17, 2014 </p>
	 * @version V1.0  
	 */
	public ResMessage queryResource(ReqMessage reqMessage) {
		logger.info("[ResourceServiceBean]queryResource请求数据："+reqMessage);
		//上次请求数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "ResourceServiceBean.queryResource.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResourceDao resourceDao = BeanManager.getBean("resourceDao", ResourceDao.class);
		ResMessage res = new ResMessage();
		try {
			Integer startIndex = Integer.parseInt(reqMessage.getString(XmlData.START_INDEX));//开始记录索引
			Integer pageSize = Integer.parseInt(reqMessage.getString(XmlData.PAGE_SIZE));//每页显示条数
			Map<String, Object> reqMap=reqMessage.getReqMap();
			List<Resource> resource =resourceDao.findPageList(reqMap, startIndex, pageSize);
			Integer totalNum = resourceDao.findPageList_count(reqMap);
			res.put(XmlData.RESULT_LIST, resource);
			res.put(XmlData.TOTAL_NUM, totalNum);
			res.setRetCode(RetCode.SUCCESS);
			res.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			res.setRetCode(RetCode.DB_ERROR);
			res.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			res.setRetCode(RetCode.UNKNOWN);
			res.setRetMsg("未知错误");
		}
		logger.info("[ResourceServiceBean]queryResource响应数据："+res);
		return res;
	}

	public ResMessage modifyResourse(ReqMessage reqMessage) {
		logger.info(String.format("[资源修改]请求参数：%s", reqMessage.toString()));
		ResMessage res = new ResMessage();
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "ResourceServiceBean.modifyResourse.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResourceDao resourceDao = BeanManager.getBean("resourceDao", ResourceDao.class);
		try {
			resourceDao.updateResource(reqMessage.getReqMap());
			res.setRetCode(RetCode.SUCCESS);
			res.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error("[资源修改]异常：数据错误!",e);
			res.setRetCode(RetCode.DB_ERROR);
			res.setRetMsg("数据错误");
		} catch (BusinessException e) {
			logger.error(String.format("[资源修改]异常，错误码：%s,错误信息%s。",e.getCode(),e.getMessage()));
			res.setRetCode(e.getCode());
			res.setRetMsg(e.getMessage());
		} catch (Exception e) {
			logger.error("[资源修改]未知异常",e);
			res.setRetCode(RetCode.UNKNOWN);
			res.setRetMsg("未知异常");
		}
		return res;
	}

	public ResMessage deleteResourse(ReqMessage reqMessage) {
		ResMessage res = new ResMessage();
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "ResourceServiceBean.deleteResourse.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResourceDao resourceDao = BeanManager.getBean("resourceDao", ResourceDao.class);
		try {
			resourceDao.deleteResource(reqMessage.getReqMap());
			res.setRetCode(RetCode.SUCCESS);
			res.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error("[资源删除]异常：数据错误!",e);
			res.setRetCode(RetCode.DB_ERROR);
			res.setRetMsg("数据错误");
		} catch (BusinessException e) {
			logger.error(String.format("[资源删除]异常，错误码：%s,错误信息%s。",e.getCode(),e.getMessage()));
			res.setRetCode(e.getCode());
			res.setRetMsg(e.getMessage());
		} catch (Exception e) {
			logger.error("[资源删除]未知异常",e);
			res.setRetCode(RetCode.UNKNOWN);
			res.setRetMsg("未知异常");
		}
		return res;
	}

	public ResMessage addResourse(ReqMessage reqMessage) {
		ResMessage res = new ResMessage();
		logger.info(String.format("[ResourceServiceBean]addResMessage请求参数：%s", reqMessage.toString()));
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "ResourceServiceBean.addResMessage.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		Short sysId = Short.parseShort(reqMessage.getString(XmlData.SYSID));//系统编号
		String operUserId=reqMessage.getString(XmlData.OPERUSERID);
		Short flag = 0;
		int resId = -1;
		User operUser=null;
		try {
			resId = SeqUtil.genSequence(Constants.RESOURCE_SEQ)+1000;//+100的是新添加，否则就是初始化sql生成 
			logger.info(String.format("[添加资源]资源编号为：%s", resId));
			//查询操作员
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			UserDao userDao = BeanManager.getBean("userDao", UserDao.class);
			operUser = userDao.getUser(qryMap);
			if(operUser == null)throw new BusinessException(RetCode.NO_DATA,"操作员不存在！");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			res.setRetCode(RetCode.DB_ERROR);
			res.setRetMsg("数据库出错");
		}  catch (BusinessException e) {
			logger.error(String.format("[添加资源]生成资源编号异常,retCode=%s,retMsg=%s", e.getCode(),e.getMessage()));
			res.setRetCode(e.getCode());
			res.setRetMsg(e.getMessage());
			return res;
		}
		
		
		Resource resource = new Resource();
		
		resource.setResId(resId);
		resource.setResName(reqMessage.getString(XmlData.RESOURCES_NAME));
		resource.setResPath(reqMessage.getString(XmlData.RESOURCES_PATH));
		resource.setCheckFlag(reqMessage.getString(XmlData.CHECK_FLAG));
		resource.setCreator(operUser.getMediaId());
		resource.setDescription(reqMessage.getString(XmlData.DESCRIPTION));
		resource.setSysId(sysId);
		resource.setFlag(flag);
		resource.setModUser(operUser.getMediaId());
		ResourceDao resourceDao = BeanManager.getBean("resourceDao", ResourceDao.class);
		try {
			resourceDao.insterResource(resource);
			res.setRetCode(RetCode.SUCCESS);
			res.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error("[添加资源]数据库异常：", e);
			res.setRetCode(RetCode.DB_ERROR);
			res.setRetMsg("数据库错误");
		}catch (Exception e) {
			logger.error("[添加资源]未知异常：", e);
			res.setRetCode(RetCode.UNKNOWN);
			res.setRetMsg("未知异常");
		}
		return res;
	}
}
